// pages/run/run.js
import WxValidate from "../../utils/WxValidate";
import utils from "../../utils/util";
const { showValidateModal, cklogin } = require("../../utils/showValidateModal");
const app = getApp();
Page({
  handleFooter() {
    wx.showModal({
      cancelColor: "cancelColor",
      title: "用户需知",
      content: "这里是隐私条款具体内容",
      showCancel: false,
    });
  },
  //选择快递商家
  bussinessChange(e) {
    const index = e.detail.value;
    this.setData({
      bussinessIndex: index,
      "form.bussiness": this.data.bussinessArray[index],
    });
  },
  /* 跳转地址 */
  handleaddress() {
    wx.navigateTo({
      url: "../address/address",
    });
  },
  //取件信息、备注信息 输入框防抖
  timeID: 0, //定时器ID
  handleInput(e) {
    const { name } = e.currentTarget.dataset;
    const { value } = e.detail;
    clearTimeout(this.timeID); //清楚timeID对应的定时器，即取消相应函数的执行
    this.timeID = setTimeout(() => {
      if (name === "expressInfo") {
        this.setData({ "form.expressInfo": value });
      } else {
        this.setData({ "form.mark": value });
      }
    }, 1000);
  },

  /**
   * 页面的初始数据
   */
  data: {
    bussinessArray: [
      "请选择快递点",
      "圆通速递(校外)",
      "顺丰快递(正大门)",
      "百世快递 (小北门)",
      "中通快递(小北门)",
      "邮政包裹(校外)",
    ], //快递商家数组
    bussinessIndex: 0, //选中得快递商家数组下标
    form: {
      address: "", //收件地址
      bussiness: "", //快递商家
      expressInfo: "", //代寄信息
      mark: "无", //备注信息
      payMoney: 3, //最终付款金额，默认3元为小件的金额
    },
    baseMoney: 3, //赏金
  },
  //计算金额
  countMoney(e) {
    //获取输入金额
    let money = e.detail.value;
    //判断是否为数字
    if (isNaN(money)) {
      wx.showToast({ title: "请输入正确金额。", icon: "error" });
      return false;
    }
    if (money.trim() != "") {
      money = Number(money) + Number(this.data.baseMoney);
      this.setData({ "form.payMoney": money });
    } else {
      this.setData({ "form.payMoney": 3 });
    }
  },
  //提交表单
  async submitForm() {
    // console.log(this.data.form.payMoney);
    //判断当前用户是否已授权登录
    const r = await cklogin(app.globalData.userInfo);
    if (!r) {
      return false;
    }
    const { address, bussiness, expressInfo, mark, payMoney } = this.data.form;
    //判断 地址、商家是否已获取
    const params = { address, bussiness };
    if (!this.WxValidate.checkForm(params)) {
      const errors = this.WxValidate.errorList[0];
      showValidateModal(errors);
      return false;
    }
    //检查 取件信息
    if (!expressInfo) {
      wx.showModal({
        title: "提示",
        content: "请输入取件码或上传截图",
        showCancel: false,
      });
      return false;
    }
    //声明发布数据时间变量，值为当前时间
    const publicTime = utils.formatTime(new Date());
    //保存数据库
    wx.showLoading({});
    wx.request({
      url: `${app.globalData.server}/addOrder`,
      method: "POST",
      data: {
        orderType: "快递代寄",
        openid: app.globalData.userInfo.openid,
        endAddress: address,
        //目的地
        startAddress: `快递点-${bussiness}`,
        //起点
        payMoney,
        //支付金额
        status: "待帮助",
        completed: "未完成",
        isCompleted: true,
        //订单状态
        publicTime,
        //发布时间
        info: {
          //其他信息
          expressInfo, //取件信息
          mark, //备注信息
        },
        userInfo: app.globalData.userInfo, //发布者的个人信息
      },
      success: (res) => {
        wx.hideLoading({});
        if (res.data == "success") {
          wx.showToast({ title: "提交成功", icon: "success" });
          setTimeout(() => {
            wx.switchTab({ url: "../order/order" });
          }, 1000);
        } else {
          wx.hideLoading({});

          wx.showToast({ title: "发布失败", icon: "error" });
        }
      },
      fail: (err) => {
        wx.hideLoading({});
        wx.showToast({ title: "发布失败", icon: "error" });
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initValidate();
  },
  initValidate() {
    // 验证字段的规则
    const rules = {
      address: { required: true },
      bussiness: { required: true },
    };
    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      address: { required: "请选择收件地址" },
      bussiness: { required: "请选择快递商家" },
    };
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
